package com.baidu.health.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baidu.health.pojo.ImgInfo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public Object upload(MultipartFile file) {
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI5tRXseLrFKDpJtYhyAZk";
        String accessKeySecret = "38Oz7jRA0x2g1yTVMqm9PAKoQK3dof";
        String bucketName = "babatuosi";

        //原始文件名
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        //UUID新文件名
        String newName = UUID.randomUUID().toString() + suffix;
        String url=null;


        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        List<ImgInfo> list=new ArrayList<>();
        ImgInfo imgInfo = new ImgInfo();
        Map<String,Object> map=new HashMap<>();
        try {
            ossClient.putObject(bucketName, newName, file.getInputStream());
            url="https://babatuosi.oss-cn-beijing.aliyuncs.com/"+newName;
        } catch (IOException e) {
            map.put("errno",-1);
            map.put("data",list);
            e.printStackTrace();
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        imgInfo.setUrl(url);
        System.out.println("图片"+url);
        list.add(imgInfo);
        map.put("errno",0);
        map.put("data",list);
        return map;
    }
}
